<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import Login from './components/Login.vue'
import Dashboard from './components/Dashboard.vue'
import DrugList from './components/DrugList.vue'
import DrugCategories from './components/DrugCategories.vue'
import Inventory from './components/Inventory.vue'
import StockIn from './components/StockIn.vue'
import StockOut from './components/StockOut.vue'
import Sales from './components/Sales.vue'
import Returns from './components/Returns.vue'
import SystemAlert from './components/SystemAlert.vue'
import Reports from './components/Reports.vue'
import Settings from './components/Settings.vue'

// 响应式数据
// 登录状态管理
const isLoggedIn = ref(false)
const currentUser = ref<{ username: string; role: string; name: string } | null>(null)

const activeMenu = ref('dashboard')
const activeNavItem = ref('dashboard')
const contentTitle = ref('系统仪表板')
const currentTime = ref('')
const lastSyncTime = ref('')

// 菜单配置
const menus = [
  { key: 'dashboard', title: '系统概览' },
  { key: 'drugs', title: '药品管理' },
  { key: 'inventory', title: '库存管理' },
  { key: 'sales', title: '销售管理' },
  { key: 'reports', title: '统计报表' },
  { key: 'settings', title: '系统设置' }
]

// 优化后的导航配置 - 消除冗余，简化结构
const navGroups = [
  {
    title: '系统概览',
    menuKey: 'dashboard',
    items: [
      { key: 'dashboard', title: '仪表板', menuKey: 'dashboard' },
      { key: 'alerts', title: '系统警告', menuKey: 'dashboard' }
    ]
  },
  {
    title: '药品管理',
    menuKey: 'drugs',
    items: [
      { key: 'drug-list', title: '药品列表', menuKey: 'drugs' },
      { key: 'drug-categories', title: '药品分类', menuKey: 'drugs' }
    ]
  },
  {
    title: '库存管理',
    menuKey: 'inventory',
    items: [
      { key: 'inventory-overview', title: '库存概览', menuKey: 'inventory' },
      { key: 'stock-in', title: '入库管理', menuKey: 'inventory' },
      { key: 'stock-out', title: '出库管理', menuKey: 'inventory' }
    ]
  },
  {
    title: '销售管理',
    menuKey: 'sales',
    items: [
      { key: 'pos', title: '收银销售', menuKey: 'sales' },
      { key: 'returns', title: '退货处理', menuKey: 'sales' }
    ]
  },
  {
    title: '统计报表',
    menuKey: 'reports',
    items: [
      { key: 'reports', title: '数据报表', menuKey: 'reports' }
    ]
  },
  {
    title: '系统设置',
    menuKey: 'settings',
    items: [
      { key: 'settings', title: '系统配置', menuKey: 'settings' }
    ]
  }
]

// 组件映射
const componentMap: Record<string, any> = {
  // 系统概览
  'dashboard': Dashboard,
  'alerts': SystemAlert,
  // 药品管理
  'drug-list': DrugList,
  'drug-categories': DrugCategories,
  // 库存管理
  'inventory-overview': Inventory,
  'stock-in': StockIn,
  'stock-out': StockOut,
  // 销售管理
  'pos': Sales,
  'returns': Returns,
  // 统计报表
  'reports': Reports,
  // 系统设置
  'settings': Settings
}

// 计算当前组件
const currentComponent = computed(() => {
  return componentMap[activeNavItem.value] || Dashboard
})

// 方法
const setActiveMenu = (menuKey: string) => {
  activeMenu.value = menuKey
  // 切换菜单时，自动选择该菜单下的第一个导航项
  const targetGroup = navGroups.find(group => group.menuKey === menuKey)
  if (targetGroup && targetGroup.items[0]) {
    const firstItem = targetGroup.items[0]
    setActiveNavItem(firstItem.key, firstItem.title)
  }
}

const setActiveNavItem = (itemKey: string, title: string) => {
  activeNavItem.value = itemKey
  contentTitle.value = title
  
  // 同步更新顶部菜单栏高亮
  // 找到该导航项对应的菜单模块
  for (const group of navGroups) {
    const targetItem = group.items.find(item => item.key === itemKey)
    if (targetItem) {
      activeMenu.value = targetItem.menuKey
      break
    }
  }
}



// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN')
  lastSyncTime.value = now.toLocaleString('zh-CN')
}

// 登录处理
const handleLogin = (userInfo: { username: string; role: string; name: string }) => {
  currentUser.value = userInfo
  isLoggedIn.value = true
  
  // 保存登录状态到localStorage
  localStorage.setItem('user_session', JSON.stringify({
    ...userInfo,
    loginTime: Date.now()
  }))
}

// 退出登录
const handleLogout = () => {
  isLoggedIn.value = false
  currentUser.value = null
  localStorage.removeItem('user_session')
  localStorage.removeItem('remembered_user')
  
  // 重置菜单状态
  activeMenu.value = 'dashboard'
  activeNavItem.value = 'dashboard'
  contentTitle.value = '系统仪表板'
}

// 检查登录状态
const checkLoginStatus = () => {
  const session = localStorage.getItem('user_session')
  if (session) {
    const userSession = JSON.parse(session)
    const loginTime = userSession.loginTime
    const currentTime = Date.now()
    
    // 检查会话是否过期（24小时）
    if (currentTime - loginTime < 24 * 60 * 60 * 1000) {
      currentUser.value = {
        username: userSession.username,
        role: userSession.role,
        name: userSession.name
      }
      isLoggedIn.value = true
    } else {
      // 会话过期，清除数据
      localStorage.removeItem('user_session')
    }
  }
}

onMounted(() => {
  checkLoginStatus()
  updateTime()
  setInterval(updateTime, 1000)
})
</script>

<template>
  <!-- 登录界面 -->
  <Login v-if="!isLoggedIn" @login="handleLogin" />
  
  <!-- 主系统界面 -->
  <div v-else class="medical-system">
    <!-- 顶部菜单栏 -->
    <div class="menu-bar">
      <!-- 左侧菜单项 -->
      <div class="menu-left">
        <div 
          v-for="menu in menus" 
          :key="menu.key"
          class="menu-item"
          :class="{ active: activeMenu === menu.key }"
          @click="setActiveMenu(menu.key)"
        >
          {{ menu.title }}
        </div>
      </div>
      
      <!-- 中间时钟显示区域 -->
      <div class="time-display">
        <div class="current-time">{{ currentTime }}</div>
      </div>
      
      <!-- 右侧用户信息 -->
      <div class="user-info">
        <span>康复药店医药管理系统 | 当前用户: {{ currentUser?.name || '未登录' }}</span>
        <button v-if="isLoggedIn" @click="handleLogout" class="logout-btn">退出</button>
      </div>
    </div>

    <!-- 主布局 -->
    <div class="main-layout">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div v-for="group in navGroups" :key="group.title" class="nav-group">
          <div class="nav-group-title">{{ group.title }}</div>
          <div 
            v-for="item in group.items" 
            :key="item.key"
            class="nav-item"
            :class="{ active: activeNavItem === item.key }"
            @click="setActiveNavItem(item.key, item.title)"
          >
            {{ item.title }}
          </div>
        </div>
      </div>

      <!-- 主工作区 -->
      <div class="main-content">
        <div class="content-header">{{ contentTitle }}</div>
        <div class="content-body">
          <component :is="currentComponent" />
        </div>
      </div>
    </div>

    <!-- 状态栏 -->
    <div class="status-bar">
      <div class="status-item">系统状态: 正常运行</div>
      <div class="status-item">数据库连接: 正常</div>
      <div class="status-item">最后同步: {{ lastSyncTime }}</div>
      <div class="status-right">
        <div class="status-item">内存使用: 65%</div>
        <div class="status-item">网络: 正常</div>
      </div>
    </div>
  </div>
</template>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

#app {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  position: absolute;
  top: 0;
  left: 0;
}
</style>

<style scoped>
.medical-system {
  font-family: 'Microsoft YaHei', 'Segoe UI', Arial, sans-serif;
  font-size: 12px;
  background: #f5f5f5;
  color: #333;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 顶部菜单栏 */
.menu-bar {
  background: #2c3e50;
  color: white;
  height: 35px;
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0 15px;
  font-size: 13px;
  box-sizing: border-box;
  position: relative;
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-item {
  padding: 8px 15px;
  cursor: pointer;
  border-radius: 3px;
  transition: background 0.2s;
}

.menu-item:hover {
  background: rgba(255,255,255,0.1);
}

.menu-item.active {
  background: #3498db;
}

/* 中间时钟显示区域 */
.time-display {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.current-time {
  font-size: 16px;
  font-weight: bold;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
  text-shadow: 0 0 5px rgba(231, 76, 60, 0.3);
}

.user-info {
  margin-left: auto;
  font-size: 12px;
  color: #ecf0f1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.logout-btn {
  background: rgba(231, 76, 60, 0.8);
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  font-size: 11px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.logout-btn:hover {
  background: #e74c3c;
}



/* 主布局 */
.main-layout {
  display: flex;
  flex: 1;
  width: 100%;
  height: calc(100vh - 60px);
  overflow: hidden;
}

/* 左侧导航 */
.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #bdc3c7;
  overflow-y: auto;
  flex-shrink: 0;
}

.nav-group {
  border-bottom: 1px solid #ecf0f1;
}

.nav-group-title {
  background: #f8f9fa;
  padding: 8px 12px;
  font-weight: bold;
  font-size: 11px;
  color: #666;
  text-transform: uppercase;
  margin: 0;
}

.nav-item {
  padding: 8px 12px 8px 25px;
  cursor: pointer;
  border-bottom: 1px solid #f8f9fa;
  font-size: 13px;
  margin: 0;
}

.nav-item:hover {
  background: #e8f4f8;
}

.nav-item.active {
  background: #3498db;
  color: white;
}

/* 主工作区 */
.main-content {
  flex: 1;
  background: white;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0;
}

.content-header {
  background: #f8f9fa;
  border-bottom: 1px solid #ecf0f1;
  padding: 8px 15px;
  font-weight: bold;
  font-size: 14px;
}

.content-body {
  flex: 1;
  padding: 10px 15px;
  overflow-y: auto;
}

/* 状态栏 */
.status-bar {
  background: #f8f9fa;
  border-top: 1px solid #ddd;
  height: 25px;
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0 15px;
  font-size: 11px;
  color: #666;
  box-sizing: border-box;
}

.status-item {
  margin-right: 20px;
}

.status-right {
  margin-left: auto;
  display: flex;
}

/* 响应式 */
@media (max-width: 1200px) {
  .sidebar {
    width: 240px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 200px;
  }
  
  .search-box input {
    width: 150px;
  }
  
  .content-body {
    padding: 10px;
  }
}
</style>
